<template>
    <card dis-hover>
        <i-form inline :label-width="60" class="search-column">
            <form-item label="用户名">
                <i-input v-model="search.username" clearable placeholder="请输入"/>
            </form-item>
            <form-item label="名称">
                <i-input v-model="search.name" clearable placeholder="请输入"/>
            </form-item>
            <form-item label="角色">
                <i-select v-model="roles.value" multiple>
                    <i-option v-for="item in roles.list" :value="item._id" :key="item._id">{{ item.name }}</i-option>
                </i-select>
            </form-item>
            <form-item :label-width="0">
                <i-button :loading="loading" type="primary" icon="ios-search" @click="getUserFn">搜索</i-button>
                <i-button type="success" icon="md-add" @click="handlerCreateUser">新增</i-button>
            </form-item>
        </i-form>
        <i-table stripe border :loading="loading" :columns="table.header" :data="table.body"/>
        <page class="pager"
              show-sizer
              :current="page.page"
              :total="page.count"
              @on-change="pageFn"
              @on-page-size-change="pageSizeChangeFn"
              prev-text="上一页"
              next-text="下一页"/>
        <!--新增用户-->
        <modal v-model="modal.show"
               :mask-closable="false"
               :styles="{top:'10px'}"
               :width="635" title="新增用户">

            <i-form :label-width="90"
                    inline
                    ref="addUserModal"
                    :model="modal.form"
                    :rules="modal.rules">
                <div>
                    <form-item label="头像">
                        <avatar-file v-model="modal.form.headImg"/>
                    </form-item>
                </div>
                <form-item label="用户名" prop="username" v-if="modal.type === 'create'">
                    <i-input v-model="modal.form.username" placeholder="请填写用户名"/>
                </form-item>
                <form-item label="密码" prop="password" v-if="modal.type === 'create'">
                    <i-input type="password" v-model="modal.form.password" placeholder="请填写用户密码"/>
                </form-item>
                <form-item label="用户昵称">
                    <i-input v-model="modal.form.name" placeholder="请填写用户昵称"/>
                </form-item>
                <form-item label="用户性别">
                    <i-select v-model="modal.form.sex" style="width: 185px;">
                        <i-option value="未知">未知</i-option>
                        <i-option value="男">男</i-option>
                        <i-option value="女">女</i-option>
                    </i-select>
                </form-item>
                <form-item label="手机号">
                    <i-input v-model="modal.form.phone" placeholder="请填写手机号"/>
                </form-item>
                <form-item label="微信号">
                    <i-input v-model="modal.form.weixin" placeholder="请填写微信号"/>
                </form-item>
                <form-item label="是否正常">
                    <div style="width: 185px;">
                        <i-switch v-model="modal.form.state" true-value="1" false-value="2"></i-switch>
                    </div>
                </form-item>
                <form-item label="用户简介" style="width: 565px;">
                    <i-input v-model="modal.form.summary" type="textarea" placeholder="请填写用户简介"/>
                </form-item>
            </i-form>
            <div slot="footer">
                <i-button @click="modal.show = false">取消</i-button>
                <i-button type="primary" @click="modalSubmitFn">确定</i-button>
            </div>
        </modal>
        <modal v-model="roles.show" :footer-hide="true" title="配置角色">
            <spin fix v-show="roles.loading"></spin>
            <div class="text-center">
                <Transfer
                        :data="roles.list"
                        class="text-left"
                        style="display: inline-block"
                        :target-keys="roles.activeList"
                        @on-change="rolesChangeFn"></Transfer>
            </div>
        </modal>
    </card>
</template>
<script>
    import API from '../../lib/API_PATH'
    import AvatarFile from '../../components/avatar-file'

    const addFormData = {
        name: '',
        username: '',
        password: '',
        sex: '未知',
        phone: '',
        summary: '',
        headImg: '',
        weixin: '',
        state: '1',
    }
    export default {
        name: 'User',
        data() {
            return {
                search: {
                    username: '',
                    name: '',
                    role: []
                },
                table: {
                    header: [
                        {
                            type: 'index',
                            width: 60
                        },
                        {
                            title: '用户名',
                            key: 'username'
                        },
                        {
                            title: '昵称',
                            key: 'name'
                        },
                        {
                            title: '性别',
                            key: 'sex'
                        },
                        {
                            title: '微信',
                            key: 'weixin'
                        },
                        {
                            title: '用户状态',
                            render: (h, params) => {
                                const state = params.row.state
                                let text = ['已删除', '正常', '已封禁']
                                return h('span', {}, text[state])
                            }
                        },
                        {
                            title: '角色',
                            render: (h, params) => {
                                if (params.row.role) {
                                    const roleArr = params.row.role.map(item => {
                                        return item.name
                                    })
                                    return h('span', {}, roleArr.join())
                                }
                            }
                        },
                        {
                            title: '操作',
                            width: 270,
                            render: (h, params) => {
                                const row = params.row
                                const state = row.state
                                const id = row._id
                                const text = state === '1' ? '封禁' : '解封'
                                const restBtn = h('Button', {
                                    props: {
                                        type: 'warning',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            this.$Modal.confirm({
                                                title: '您确定要重置此用户的密码吗？',
                                                onOk: () => {
                                                    this.restPasswordFn(id)
                                                }
                                            })
                                        }
                                    }
                                }, '重置密码')
                                const editBtn = h('Button', {
                                    props: {
                                        type: 'warning',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            this.modal.show = true
                                            this.modal.type = "edit"
                                            for (let i in this.modal.form) {
                                                this.modal.form[i] = row[i]
                                            }
                                            this.modal.form.id = id
                                        }
                                    }
                                }, '修改')
                                const roleBtn = h('Button', {
                                    props: {
                                        type: 'info',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            this.roles.show = true
                                            this.roles.id = id
                                            let role = row.role
                                            this.roles.activeList = []
                                            for (let i of role) {
                                                this.roles.activeList.push(i._id)
                                            }
                                        }
                                    }
                                }, '角色配置')
                                let setStatusBtn = h('Button', {
                                    props: {
                                        type: state === '1' ? 'error' : 'success',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            this.$Modal.confirm({
                                                title: `您确定要${text}这个用户吗？`,
                                                onOk: () => {
                                                    let sta = '1'
                                                    state === '1' ? sta = '2' : true
                                                    this.setUserStatusFn(id, sta)
                                                }
                                            })
                                        }
                                    }
                                }, text)
                                return h('button-group', [
                                    restBtn,
                                    editBtn,
                                    row.root ? true : roleBtn,
                                    row.root ? true : setStatusBtn,
                                ])
                            }
                        }
                    ],
                    body: [],
                },
                page: {
                    count: 0,
                    page: 1,
                    currentPage: 10
                },
                loading: false,
                modal: {
                    show: false,
                    type: 'create',
                    form: this.$utils.deepClone(addFormData),
                    rules: {
                        username: [
                            {required: true, min: 6, message: '用户名至少为6位', trigger: 'blur'},
                        ],
                        password: [
                            {required: true, min: 6, message: '密码至少为6位', trigger: 'blur'},
                        ]
                    }
                },
                roles: {
                    list: [],
                    activeList: [], // 待添加为管理员
                    value: [],
                    show: false,
                    id: '',
                    admin: '',
                    loading: false,
                    timer: null
                }
            }
        },
        computed: {
            userinfo() {
                return this.$store.state.user.info
            }
        },
        created() {
            this.getUserFn()
            this.$http(API.ROLE, {currentPage: 100}).then(res => {
                let list = res.data.list
                this.roles.admin = res.data.admin
                for (let i of list) {
                    i.key = i._id
                    i.label = i.name
                    i.disabled = res.data.admin === i._id
                }
                this.roles.list = list
            })
        },
        mounted() {
        },
        methods: {
            async handlerCreateUser() {
                this.modal.show = true
                this.modal.type = "create"
                this.modal.form = this.$utils.deepClone(addFormData)
            },
            async getUserFn() {
                this.loading = true

                let params = {
                    name: this.search.name,
                    username: this.search.username,
                    page: this.page.page,
                    currentPage: this.page.currentPage,
                }
                if (this.roles.value.length > 0) {
                    params.role = this.roles.value.join()
                }
                try {
                    const {data} = await this.$http(API.USER, {params})
                    this.table.body = data.list
                    this.page.count = data.count
                    this.page.page = parseInt(data.page)
                } catch (e) {

                }
                this.loading = false
            },
            pageFn(v) {
                this.page.page = v
                this.getUserFn()
            },
            pageSizeChangeFn(v) {
                this.page.currentPage = v
                this.getUserFn()
            },
            // 新增/修改用户
            async addUserFn() {
                const req = this.modal.form
                req.state = req.state.toString()
                let method = 'post'
                let text = '新增'
                if (this.modal.type === 'edit') {
                    method = 'put'
                    text = '修改'
                }
                try {
                    const {data} = await this.$http[method](API.USER, req)
                    if (this.modal.type === 'edit' && this.modal.form.id === this.userinfo._id) {
                        this.$store.dispatch('getUserInfo')
                    }
                    this.$Message.success(text + '用户成功')
                    this.getUserFn()
                    this.modal.show = false
                    this.modal.form = this.$utils.deepClone(addFormData)

                } catch (e) {
                    console.log(e)
                    this.$utils.errMessage(e, text + '用户')
                }
            },
            modalSubmitFn() {
                if (this.modal.type === 'edit') {
                    this.addUserFn()
                    return
                }
                this.$refs.addUserModal.validate((valid) => {
                    console.log(valid)
                    if (valid) {
                        this.addUserFn()
                    }
                })
            },
            // 封禁，解封用户
            async setUserStatusFn(id, state) {
                try {
                    const {data} = await this.$http.put(API.USER_STATUS, {id, state})
                    this.getUserFn()
                    this.$Message.success(state === 1 ? '解封成功' : '封禁成功')
                } catch (e) {
                    this.$utils.errMessage(e, state === 1 ? '解封' : '封禁')
                }
            },
            // 重置密码
            async restPasswordFn(id) {
                try {
                    await this.$http.put(API.USER_REST_PASSWORD, {id})
                    this.$Message.success('密码重置成功')
                } catch (e) {
                    this.$utils.errMessage(e, '重置密码')
                }
            },
            // 角色穿梭框变化
            rolesChangeFn(newTargetKeys, direction, moveKeys) {
                console.log(newTargetKeys)
                if (newTargetKeys.length < 1 && direction === 'left') {
                    this.$Message.error('每个用户最少存在一个角色')
                    return false
                }
                this.roles.activeList = newTargetKeys
                if (direction === 'right') {
                    for (let i of moveKeys) {
                        this.userAddRoleFn(i)
                    }
                }
                if (direction === 'left') {
                    for (let i of moveKeys) {
                        this.userRemoveRoleFn(i)
                    }
                }
            },
            // 移除添加角色时的定时加载
            setTimeRoleToggleFn() {
                if (this.roles.timer) {
                    clearTimeout(this.roles.timer)
                }
                this.roles.timer = setTimeout(() => {
                    this.getUserFn()
                }, 1000)
            },
            // 为用户添加角色
            async userAddRoleFn(roleId) {
                const userId = this.roles.id
                this.roles.loading = true
                try {
                    const {data} = await this.$http.post(API.USER_CREATE_ROLE, {userId, roleId})
                    this.setTimeRoleToggleFn()
                    this.$Message.success('添加角色成功')
                } catch (e) {
                    this.$Message.error('添加角色失败')
                }
                this.roles.loading = false
            },
            // 为用户移除角色
            async userRemoveRoleFn(roleId) {
                const userId = this.roles.id
                this.roles.loading = true
                try {
                    const {data} = await this.$http.post(API.USER_DELETE_ROLE, {userId, roleId})
                    this.setTimeRoleToggleFn()
                    this.$Message.success('移除角色成功')
                } catch (e) {
                    this.$Message.error('移除角色失败')
                }
                this.roles.loading = false
            }
        },
        components: {
            AvatarFile
        }
    }
</script>
<style lang="scss">

</style>
